'use client';
import React, { useState } from 'react';
import { LockOutlined, UserOutlined, EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons';
import { Button, Checkbox, Form, Input, Card, Typography, message, Spin } from 'antd';
import { useRouter } from 'next/navigation';
import { authService, LoginResponse } from '@/service/auth';
import { useAuth } from '../layout-content';

const { Title, Text } = Typography;

interface LoginFormData {
  username: string;
  password: string;
  remember?: boolean;
}

/**
 * 管理员登录页面
 * 使用专属的管理员登录接口，确保只有管理员角色能登录
 */
export default function AdminLoginPage() {
  const router = useRouter();
  const { login } = useAuth();
  const [form] = Form.useForm<LoginFormData>();
  const [loading, setLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);

  /**
   * 处理表单提交
   * 使用认证服务进行登录
   */
  const handleSubmit = async (values: LoginFormData) => {
    setLoading(true);
    
    try {
      // 调用认证服务的登录方法
      const response: LoginResponse = await authService.login(values);

      if (response.code === 200 || !response.code) {
        const { access_token, admin } = response.data || response;
        
        if (access_token && admin) {
          // 使用auth hook进行登录，保存token和用户信息
          // 服务端返回的 admin 对象不含 password，构造本地 User 类型所需字段
          const user = { ...admin, password: '' };
          login(access_token, user);
          
          // 显示成功提示
          message.success('登录成功，正在跳转...');
          
          // 跳转到管理后台首页
          setTimeout(() => {
            router.push('/');
          }, 1000);
        } else {
          message.error('登录失败：返回数据格式错误');
        }
      } else {
        message.error(`登录失败：${response.message || '未知错误'}`);
      }
    } catch (error: any) {
      // 错误处理
      if (error.message.includes('401') || error.message.includes('用户名或密码错误')) {
        message.error('用户名或密码错误');
      } else if (error.message.includes('403') || error.message.includes('管理员')) {
        message.error('只有管理员才能登录管理后台');
      } else {
        message.error(`登录失败：${error.message || '网络错误'}`);
      }
    } finally {
      setLoading(false);
    }
  };

  /**
   * 切换密码可见性
   */
  const togglePasswordVisibility = () => {
    setShowPassword(!showPassword);
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-100 to-gray-200 p-4">
      <Card 
        className="w-full max-w-md shadow-lg rounded-xl overflow-hidden border-0"
        style={{ borderRadius: '16px' }}
      >
        <div className="p-8">
          {/* 登录标题 */}
          <div className="text-center mb-8">
            <Title level={2} className="mb-2 text-gray-800 font-bold">
              管理员登录
            </Title>
            <Text className="text-gray-500">
              请使用管理员账号登录系统
            </Text>
          </div>

          {/* 登录表单 */}
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
            initialValues={{
              remember: true,
            }}
          >
            {/* 用户名输入框 */}
            <Form.Item
              name="username"
              label="用户名"
              rules={[
                { required: true, message: '请输入用户名' },
                { min: 3, max: 20, message: '用户名长度应在3-20个字符之间' },
              ]}
              className="mb-4"
              initialValue="admin"
            >
              <Input
                prefix={<UserOutlined className="text-gray-400" />}
                placeholder="请输入管理员用户名"
                className="rounded-lg h-11"
                disabled={loading}
              />
            </Form.Item>

            {/* 密码输入框 */}
            <Form.Item
              name="password"
              label="密码"
              rules={[
                { required: true, message: '请输入密码' },
                { min: 6, message: '密码长度至少为6个字符' },
              ]}
              className="mb-4"
              initialValue="123456"
            >
              <Input.Password
                prefix={<LockOutlined className="text-gray-400" />}
                placeholder="请输入密码"
                iconRender={(visible) => 
                  visible ? 
                    <EyeOutlined onClick={togglePasswordVisibility} /> : 
                    <EyeInvisibleOutlined onClick={togglePasswordVisibility} />
                }
                className="rounded-lg h-11"
                disabled={loading}
              />
            </Form.Item>

            {/* 记住我选项 */}
            <Form.Item
              name="remember"
              valuePropName="checked"
              wrapperCol={{ offset: 0 }}
              className="mb-6"
            >
              <Checkbox className="text-gray-600">记住我</Checkbox>
            </Form.Item>

            {/* 登录按钮 */}
            <Form.Item className="mb-4">
              <Button
                type="primary"
                htmlType="submit"
                className="w-full h-11 text-lg"
                loading={loading}
                style={{
                  backgroundColor: '#1677ff',
                  borderColor: '#1677ff',
                }}
              >
                {loading ? <Spin size="small" /> : '登录'}
              </Button>
            </Form.Item>
          </Form>

          {/* 页脚信息 */}
          <div className="text-center text-gray-500 text-sm mt-6">
            <p>© 2024 管理后台系统 - 仅供管理员使用</p>
          </div>
          <div className="text-center text-gray-500 text-sm mt-2" style={{mask: 'linear-gradient(to right, rgba(0,0,0,0) 0%, rgba(0,0,0,0.5) 50%, rgba(0,0,0,0) 100%)'}}>
            <p>联系管理员：<a href="mailto:admin@example.com" className="text-blue-500">admin@example.com</a></p>
          </div>
        </div>
      </Card>
    </div>
  );
}
